package com.boyinet.demo.pipelineleakage.controller;

import com.boyinet.demo.pipelineleakage.common.R;
import com.boyinet.demo.pipelineleakage.exception.UnauthorizedException;
import com.boyinet.demo.pipelineleakage.vo.LoginResponse;
import com.boyinet.demo.pipelineleakage.vo.User;
import com.google.common.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping()
public class UserController {

    private static final String USER_NAME = "admin";

    private static final String PASSWD = "1234578";

    private static final String AVATAR = "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png";

    private final Cache<String, String> tokenCache;

    public UserController(Cache<String, String> tokenCache) {
        this.tokenCache = tokenCache;
    }

    @RequestMapping("/login/account")
    public LoginResponse login(String username, String password, String type) {
        if (USER_NAME.equals(username) && PASSWD.equals(password)) {
            tokenCache.put(username, username);
            return LoginResponse.ok(type);
        } else {
            return LoginResponse.error(type);
        }
    }


    @RequestMapping("/currentUser")
    public R<User> currentUser() {
        String s = tokenCache.getIfPresent(USER_NAME);
        if (s == null) {
            throw new UnauthorizedException();
        } else {
            return R.ok(new User(USER_NAME, AVATAR, "000001"));
        }
    }

    @RequestMapping("/login/outLogin")
    public R<Void> outLogin() {
        tokenCache.invalidate(USER_NAME);
        return R.ok();
    }
}
